package priv.winnine.service.impl;

import org.springframework.stereotype.Service;
import priv.winnine.entity.bo.DeveloperInfo;
import priv.winnine.entity.bo.RequestInfo;
import priv.winnine.entity.enums.ResultEnum;
import priv.winnine.exception.ResultException;
import priv.winnine.service.AuthService;
import priv.winnine.util.AuthUtil;

import java.util.regex.Pattern;

@Service
public class AuthServiceImpl implements AuthService {

    @Override
    public DeveloperInfo getDeveloperInfoBySid(String sid) {
        DeveloperInfo developerInfo = DeveloperInfo.builder()
                .sid(sid)
                .authToken("2f4baba15ad9b36766d84608da3a1b76")
                .enterpriseCode("am5454")
                .DeveloperId(1)
                .pathPattern("/test/.*,/common/.*")
                .build();
        // TODO 从数据库中查询，目前是写死
        return developerInfo;
    }

    @Override
    public void checkSignatureAndPath(String path, RequestInfo requestInfo, DeveloperInfo developerInfo) {
        String signature = AuthUtil.generateSignature(developerInfo.getSid(), developerInfo.getAuthToken(), requestInfo.getTimestamp());
        if (!signature.equals(requestInfo.getSignature())) {
            throw new ResultException(ResultEnum.SIGNATURE_CHECK_FAIL);
        }
        if (!AuthUtil.match(path, developerInfo.getPathPattern())) {
            throw new ResultException(ResultEnum.INSUFFICIENT_AUTHORITY);
        }
    }

    @Override
    public boolean checkAppID(String sid, String appID) {
        // TODO 待实现
        return true;
    }
}
